import { defineStore } from 'pinia';
import { ref } from 'vue';
import api from '@/http/api';
import emitter from "@/utils/bus";

export const useMenuBadgeStore = defineStore('menuBadge', () => {
  const badgeScriptId = ref(null);
  const loading = ref(false);
  const loaded = ref(false);
  const menuBadges = ref({});

  const initMenuBadge = async(scriptId) => {
    if (scriptId) {
      badgeScriptId.value = scriptId;
      await getMenuBadges();
    }
  };

  const getMenuBadges = async() => {
    if (!badgeScriptId.value) return {};

    if (loaded.value) {
      return menuBadges.value || {};
    }

    if (loading.value) {
      await sleep(100);
      return await getMenuBadges();
    }

    loading.value = true;
    try {
      let res = await api.runScript(badgeScriptId.value);
      menuBadges.value = res.data || {};
      loading.value = false;
      loaded.value = true;

      emitter.off("menu.data.change", clearMenuBadges);
      emitter.on("menu.data.change", clearMenuBadges);
      return menuBadges.value;
    } finally {
      loading.value = false;
    }
  };

  const clearMenuBadges = (menuId) => {
    if(menuBadges.value[menuId]) {
      menuBadges.value = {};
      loaded.value = false;
    }
  };

  const sleep = async (d) => {
    return new Promise((resolve) => setTimeout(resolve, d))
  };

  return { getMenuBadges, initMenuBadge };
});
